package com.ruoyi.web.controller.home;


import com.github.pagehelper.PageInfo;
import com.ruoyi.system.domain.News;
import com.ruoyi.system.service.NewsService;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/news")
public class NewsController {

    private final NewsService newsService;

    public NewsController(NewsService newsService) {
        this.newsService = newsService;
    }

    @GetMapping("/list")
    public PageInfo<News> list(@RequestParam int pageNum, @RequestParam int pageSize) {
        return newsService.findAll(pageNum, pageSize);
    }

    @GetMapping("/{id}")
    public News get(@PathVariable Integer id) {
        return newsService.findById(id);
    }

    @PostMapping
    public Result<?> save(@RequestBody News news) {
        if (!newsService.checkTitle(news.getTitle(), null)) {
            return Result.error("标题已存在");
        }
        return newsService.save(news) ? Result.success() : Result.error("保存失败");
    }

    @PutMapping
    public Result<?> update(@RequestBody News news) {
        if (!newsService.checkTitle(news.getTitle(), news.getId())) {
            return Result.error("标题已存在");
        }
        return newsService.update(news) ? Result.success() : Result.error("更新失败");
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Integer id) {
        return newsService.delete(id) ? Result.success() : Result.error("删除失败");
    }




    static class Result<T> {
        private int code;
        private String message;
        private T data;

        private Result() {}

        static <T> Result<T> success() {
            Result<T> r = new Result<>();
            r.code = 200;
            r.message = "成功";
            return r;
        }

        static <T> Result<T> success(T data) {
            Result<T> r = success();
            r.data = data;
            return r;
        }

        static Result<?> error(String message) {
            Result<?> r = new Result<>();
            r.code = 500;
            r.message = message;
            return r;
        }
    }
}
